import { defineStore } from 'pinia'
import { ref, watch } from 'vue'
import type { AppSettings } from '@/types/settings'

const DEFAULT_SETTINGS: AppSettings = {
  general: {
    theme: 'auto',
    language: 'zh-CN',
    autoSave: true
  },
  conversion: {
    defaultOutputFormat: 'pdf',
    defaultQuality: 'medium',
    autoDownload: false,
    keepOriginalFiles: true
  },
  notification: {
    enableDesktop: true,
    enableSound: false,
    enableEmail: false
  },
  storage: {
    autoCleanup: true,
    maxStorageSize: 1024, // MB
    retentionDays: 30
  },
  advanced: {
    concurrentTasks: 3,
    timeout: 300000, // 5 minutes
    debugMode: false,
    apiEndpoint: import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000'
  }
}

export const useSettingsStore = defineStore('settings', () => {
  // 状态
  const settings = ref<AppSettings>({ ...DEFAULT_SETTINGS })
  const loading = ref(false)
  const error = ref<string | null>(null)

  // 方法
  const loadSettings = () => {
    try {
      const savedSettings = localStorage.getItem('app_settings')
      if (savedSettings) {
        const parsed = JSON.parse(savedSettings)
        settings.value = { ...DEFAULT_SETTINGS, ...parsed }
      }
      
      // 应用主题
      applyTheme()
    } catch (err) {
      console.error('Failed to load settings:', err)
      settings.value = { ...DEFAULT_SETTINGS }
    }
  }

  const saveSettings = async (newSettings?: Partial<AppSettings>) => {
    loading.value = true
    error.value = null
    
    try {
      if (newSettings) {
        settings.value = { ...settings.value, ...newSettings }
      }
      
      // 保存到本地存储
      localStorage.setItem('app_settings', JSON.stringify(settings.value))
      
      // 应用设置
      applySettings()
      
    } catch (err: any) {
      error.value = '保存设置失败'
      console.error('Failed to save settings:', err)
    } finally {
      loading.value = false
    }
  }

  const updateSettings = async (newSettings: Partial<AppSettings>) => {
    return await saveSettings(newSettings)
  }

  const resetSettings = async () => {
    loading.value = true
    
    try {
      settings.value = { ...DEFAULT_SETTINGS }
      localStorage.removeItem('app_settings')
      applySettings()
    } catch (err) {
      console.error('Failed to reset settings:', err)
    } finally {
      loading.value = false
    }
  }

  const resetToDefaults = async () => {
    return await resetSettings()
  }

  const exportSettings = () => {
    try {
      const dataStr = JSON.stringify(settings.value, null, 2)
      const dataBlob = new Blob([dataStr], { type: 'application/json' })
      
      const link = document.createElement('a')
      link.href = URL.createObjectURL(dataBlob)
      link.download = 'md2dockit-settings.json'
      link.click()
      
      URL.revokeObjectURL(link.href)
    } catch (err) {
      console.error('Failed to export settings:', err)
      error.value = '导出设置失败'
    }
  }

  const importSettings = async (file: File) => {
    loading.value = true
    error.value = null
    
    try {
      const text = await file.text()
      const importedSettings = JSON.parse(text)
      
      // 验证设置格式
      if (typeof importedSettings !== 'object') {
        throw new Error('Invalid settings format')
      }
      
      // 合并设置
      settings.value = { ...DEFAULT_SETTINGS, ...importedSettings }
      
      // 保存并应用
      await saveSettings()
      
    } catch (err: any) {
      error.value = '导入设置失败：' + (err.message || '文件格式错误')
      console.error('Failed to import settings:', err)
    } finally {
      loading.value = false
    }
  }

  const applySettings = () => {
    // 应用主题设置
    const theme = settings.value.general.theme
    if (theme === 'dark') {
      document.documentElement.classList.add('dark')
    } else if (theme === 'light') {
      document.documentElement.classList.remove('dark')
    } else {
      // auto 模式，根据系统偏好设置
      const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
      if (prefersDark) {
        document.documentElement.classList.add('dark')
      } else {
        document.documentElement.classList.remove('dark')
      }
    }
    
    // 应用语言设置
    document.documentElement.lang = settings.value.general.language
  }

  const applyTheme = () => {
    const { theme } = settings.value
    const root = document.documentElement
    
    if (theme === 'auto') {
      // 检测系统主题
      const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
      root.setAttribute('data-theme', prefersDark ? 'dark' : 'light')
    } else {
      root.setAttribute('data-theme', theme)
    }
  }

  const applyLanguage = () => {
    const { language } = settings.value
    document.documentElement.lang = language
  }

  const applyNotifications = () => {
    const { desktopNotifications } = settings.value
    
    if (desktopNotifications && 'Notification' in window) {
      if (Notification.permission === 'default') {
        Notification.requestPermission()
      }
    }
  }

  const toggleTheme = () => {
    const currentTheme = settings.value.general.theme
    let newTheme: 'light' | 'dark' | 'auto'
    
    if (currentTheme === 'light') {
      newTheme = 'dark'
    } else if (currentTheme === 'dark') {
      newTheme = 'auto'
    } else {
      newTheme = 'light'
    }
    
    saveSettings({ general: { ...settings.value.general, theme: newTheme } })
  }

  const clearCache = async () => {
    loading.value = true
    
    try {
      // 清除各种缓存
      if ('caches' in window) {
        const cacheNames = await caches.keys()
        await Promise.all(
          cacheNames.map(cacheName => caches.delete(cacheName))
        )
      }
      
      // 清除本地存储中的临时数据
      const keysToRemove = []
      for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i)
        if (key && (key.startsWith('temp_') || key.startsWith('cache_'))) {
          keysToRemove.push(key)
        }
      }
      
      keysToRemove.forEach(key => localStorage.removeItem(key))
      
    } catch (err) {
      console.error('Failed to clear cache:', err)
      error.value = '清除缓存失败'
    } finally {
      loading.value = false
    }
  }

  const getStorageInfo = () => {
    try {
      let totalSize = 0
      let itemCount = 0
      
      for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i)
        if (key) {
          const value = localStorage.getItem(key)
          if (value) {
            totalSize += key.length + value.length
            itemCount++
          }
        }
      }
      
      return {
        totalSize: Math.round(totalSize / 1024), // KB
        itemCount,
        available: 5120 - Math.round(totalSize / 1024) // 假设 5MB 限制
      }
    } catch (err) {
      console.error('Failed to get storage info:', err)
      return {
        totalSize: 0,
        itemCount: 0,
        available: 5120
      }
    }
  }

  // 监听系统主题变化
  if (typeof window !== 'undefined') {
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
    mediaQuery.addEventListener('change', () => {
      if (settings.value.theme === 'auto') {
        applyTheme()
      }
    })
  }

  // 监听设置变化
  watch(
    () => settings.value.theme,
    () => applyTheme(),
    { immediate: true }
  )

  // 清除错误
  const clearError = () => {
    error.value = null
  }

  return {
    // 状态
    settings,
    loading,
    error,
    
    // 方法
    loadSettings,
    saveSettings,
    updateSettings,
    resetSettings,
    resetToDefaults,
    exportSettings,
    importSettings,
    applySettings,
    toggleTheme,
    clearCache,
    getStorageInfo,
    clearError
  }
})